import React, { useEffect, useState } from 'react';
import {
  Box,
  Container,
  Typography,
  Paper,
  TextField,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Autocomplete,
  FormControlLabel,
  Switch,
  IconButton,
  useTheme,
  SelectChangeEvent
} from '@mui/material';
import { PhotoCamera as PhotoCameraIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams } from 'react-router-dom';
import { useForm, Controller } from 'react-hook-form';
import { useGetArticleQuery, useCreateArticleMutation, useUpdateArticleMutation, useUploadCoverMutation } from '../../store/services/articles';
import { useGetCategoriesQuery } from '../../store/services/categories';
import { useGetTagsQuery } from '../../store/services/tags';
import { CreateArticleRequest, UpdateArticleRequest } from '../../types/article';
import Loading from '../../components/common/Loading';
import SimpleMDE from 'react-simplemde-editor';
import 'easymde/dist/easymde.min.css';

interface ArticleForm extends Omit<CreateArticleRequest, 'categoryId' | 'tagIds'> {
  category: { id: number; name: string } | null;
  tags: Array<{ id: number; name: string }>;
}

const ArticleEdit: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const theme = useTheme();
  const { id } = useParams<{ id: string }>();
  const isEdit = Boolean(id);

  const { data: articleResponse, isLoading: isLoadingArticle } = useGetArticleQuery(
    Number(id),
    { skip: !isEdit }
  );

  const { data: categoriesResponse } = useGetCategoriesQuery();
  const { data: tagsResponse } = useGetTagsQuery();

  const categories = categoriesResponse?.data || [];
  const tags = tagsResponse?.data || [];

  const [createArticle] = useCreateArticleMutation();
  const [updateArticle] = useUpdateArticleMutation();
  const [uploadCover] = useUploadCoverMutation();

  const [previewUrl, setPreviewUrl] = useState<string>('');

  const { control, handleSubmit, setValue, watch } = useForm<ArticleForm>({
    defaultValues: {
      title: '',
      content: '',
      summary: '',
      cover: '',
      category: null,
      tags: [],
      status: 'DRAFT'
    }
  });

  useEffect(() => {
    if (articleResponse?.data) {
      const article = articleResponse.data;
      setValue('title', article.title);
      setValue('content', article.content);
      setValue('summary', article.summary);
      setValue('cover', article.cover || '');
      setValue('category', article.category);
      setValue('tags', article.tags);
      setValue('status', article.status);
      setPreviewUrl(article.cover || '');
    }
  }, [articleResponse, setValue]);

  const handleCoverUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await uploadCover(formData).unwrap();
      setValue('cover', response.data.cover);
      setPreviewUrl(response.data.cover);
    } catch (err) {
      console.error('Upload cover failed:', err);
    }
  };

  const onSubmit = async (data: ArticleForm) => {
    const articleData = {
      title: data.title,
      content: data.content,
      summary: data.summary || data.content.slice(0, 200),
      cover: data.cover,
      categoryId: data.category?.id as number,
      tagIds: data.tags.map(tag => tag.id),
      status: data.status
    };

    try {
      if (isEdit) {
        await updateArticle({ id: Number(id), ...articleData }).unwrap();
      } else {
        await createArticle(articleData).unwrap();
      }
      navigate('/articles');
    } catch (err) {
      console.error('Save article failed:', err);
    }
  };

  if (isEdit && isLoadingArticle) {
    return <Loading />;
  }

  return (
    <Container maxWidth="lg">
      <Paper elevation={3} sx={{ p: 3, mb: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          {isEdit ? t('article.edit.title') : t('article.create.title')}
        </Typography>

        <Box component="form" onSubmit={handleSubmit(onSubmit)} sx={{ mt: 3 }}>
          <Controller
            name="title"
            control={control}
            rules={{ required: true }}
            render={({ field, fieldState: { error } }) => (
              <TextField
                {...field}
                fullWidth
                label={t('article.form.title')}
                error={!!error}
                helperText={error ? t('common.required') : ''}
                sx={{ mb: 3 }}
              />
            )}
          />

          <Box sx={{ mb: 3 }}>
            <input
              accept="image/*"
              id="cover-upload"
              type="file"
              style={{ display: 'none' }}
              onChange={handleCoverUpload}
            />
            <label htmlFor="cover-upload">
              <Button
                variant="outlined"
                component="span"
                startIcon={<PhotoCameraIcon />}
              >
                {t('article.form.uploadCover')}
              </Button>
            </label>
            {previewUrl && (
              <Box
                component="img"
                src={previewUrl}
                alt="Cover preview"
                sx={{
                  mt: 2,
                  maxWidth: '100%',
                  maxHeight: 200,
                  objectFit: 'cover'
                }}
              />
            )}
          </Box>

          <Controller
            name="category"
            control={control}
            rules={{ required: true }}
            render={({ field: { value, onChange }, fieldState: { error } }) => (
              <FormControl fullWidth error={!!error} sx={{ mb: 3 }}>
                <InputLabel>{t('article.form.category')}</InputLabel>
                <Select
                  value={value?.id || ''}
                  label={t('article.form.category')}
                  onChange={(e: SelectChangeEvent<number>) => {
                    const selectedCategory = categories.find(
                      (cat) => cat.id === e.target.value
                    );
                    onChange(selectedCategory || null);
                  }}
                >
                  {categories.map((category) => (
                    <MenuItem key={category.id} value={category.id}>
                      {category.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            )}
          />

          <Controller
            name="tags"
            control={control}
            render={({ field: { value, onChange } }) => (
              <Autocomplete
                multiple
                value={value}
                onChange={(_, newValue) => onChange(newValue)}
                options={tags}
                getOptionLabel={(option) => option.name}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label={t('article.form.tags')}
                    sx={{ mb: 3 }}
                  />
                )}
              />
            )}
          />

          <Controller
            name="content"
            control={control}
            rules={{ required: true }}
            render={({ field: { value, onChange }, fieldState: { error } }) => (
              <Box sx={{ mb: 3 }}>
                <SimpleMDE
                  value={value}
                  onChange={onChange}
                  options={{
                    spellChecker: false,
                    status: false,
                    minHeight: '400px',
                    previewClass: [
                      theme.palette.mode === 'dark' ? 'editor-dark' : 'editor-light'
                    ]
                  }}
                />
                {error && (
                  <Typography color="error" variant="caption">
                    {t('common.required')}
                  </Typography>
                )}
              </Box>
            )}
          />

          <Controller
            name="summary"
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                multiline
                rows={3}
                label={t('article.form.summary')}
                helperText={t('article.form.summaryHelp')}
                sx={{ mb: 3 }}
              />
            )}
          />

          <Controller
            name="status"
            control={control}
            render={({ field: { value, onChange } }) => (
              <FormControlLabel
                control={
                  <Switch
                    checked={value === 'PUBLISHED'}
                    onChange={(e) =>
                      onChange(e.target.checked ? 'PUBLISHED' : 'DRAFT')
                    }
                  />
                }
                label={t('article.form.publish')}
                sx={{ mb: 3 }}
              />
            )}
          />

          <Box sx={{ display: 'flex', gap: 2 }}>
            <Button
              type="submit"
              variant="contained"
              color="primary"
              size="large"
            >
              {t('common.save')}
            </Button>
            <Button
              variant="outlined"
              size="large"
              onClick={() => navigate(-1)}
            >
              {t('common.cancel')}
            </Button>
          </Box>
        </Box>
      </Paper>
    </Container>
  );
};

export default ArticleEdit; 